import { Component, ViewChild } from '@angular/core';             
import { Nav, Platform, } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { AlertController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';
import { InAppBrowser, InAppBrowserOptions } from '@ionic-native/in-app-browser';
import { HomePage } from '../pages/home/home';    
import { ListPage } from '../pages/list/list';
import { BuyPage } from '../pages/buy/buy';
import { TihuoPage } from '../pages/tihuo/tihuo';  
//我的地址 //10866l4xf27et       
import { AddressPage } from '../pages/address/address';
//我的银行卡
import { BankcardPage } from '../pages/bankcard/bankcard';
//我的银行卡
import { CardPage } from '../pages/card/card';
//卡淘淘游戏
import { KataotaoPage } from '../pages/kataotao/kataotao';
//客服
import { KefuPage } from '../pages/kefu/kefu';
//登录
import { LoginPage } from '../pages/login/login'; 
//设置
import { SettingPage } from '../pages/setting/setting';
//专卖
import { ZhuanmaiPage } from '../pages/zhuanmai/zhuanmai';
//用户中心
import { UserinfoPage } from '../pages/userinfo/userinfo';
import { Https } from './http.service';

//laun
import { RegisterPage } from '../pages/register/register';

@Component({
    templateUrl: 'app.html'
})
export class App {
    @ViewChild(Nav) nav: Nav;
  
    rootPage: any = localStorage.getItem("laun") == '0' || localStorage.getItem("laun") == null ? RegisterPage : HomePage;
    autoLoginUrl:string = new Https().Url +"act=connect&op=app_auto_login";

    aplyUrl: string = new Https().Url + "act=goods&op=app_get_user_info";
    user_name: string = '请登录';
    user_pic: string = './assets/imgs/user.png';
    user:any;
    state:any;
    pages: Array<{ title: string, img: string, component: any}>;
    User: Array<{ userName : string, img : string, component: any }>;
    loginState: number ;
    constructor(public platform: Platform, public statusBar: StatusBar, private iab: InAppBrowser,public splashScreen: SplashScreen, public alertCtrl: AlertController, private http: HttpClient,) {


        this.initializeApp();
        //0：已登录；1 : 未登录
        this.loginState = parseInt(localStorage.getItem("loginState"));
        console.log(localStorage.getItem("loginState")); 
        this.lodingItem();
        if (localStorage.getItem("userName") != null && localStorage.getItem("userPic") != null){
            this.user_name = localStorage.getItem("userName")
            this.user_pic = localStorage.getItem("userPic")
        }else{
            this.user_name  = '请登录'
            this.user_pic = './assets/imgs/user.png';
        }
        
        this.pages = [
            // { title: '首页', img: "./assets/imgs/home.png", component: HomePage },
            { title: '我的余额', img: "./assets/imgs/left_money_icon.png", component: ListPage },
            { title: '我的购买', img: "./assets/imgs/left_gouwuchei_icon.png", component: BuyPage },
            { title: '我的商品', img: "./assets/imgs/left_wodekabao_icon.png", component: CardPage },
            { title: '我的提货', img: "./assets/imgs/left_tihuo_icon.png", component: TihuoPage },            
            { title: '我的转卖', img: "./assets/imgs/zhuanmai.png", component: ZhuanmaiPage },
            // { title: '银行卡', img: "./assets/imgs/left_yinhangka_icon.png", component: BankcardPage },
            // { title: '我的地址', img: "./assets/imgs/left_dizh_icon.png", component: AddressPage },
            { title: '全民娱乐', img: "./assets/imgs/home_menu_game.png", component: KataotaoPage, },            
            { title: '联系客服', img: "./assets/imgs/kefu_icon.png", component: null },
            { title: '系统设置', img: "./assets/imgs/left_setting_icon.png", component: SettingPage },
        ];
        this.User = [
            { userName: "已登录", img: "./assets/imgs/user.png", component: UserinfoPage },
            { userName: "请登录", img: "./assets/imgs/user.png", component: LoginPage }
        ];

        //检测更新
        // let confirm = this.alertCtrl.create({
        //     title: '发现新版本',
        //     message: '是否更新？',
        //     buttons: [
        //         { text: '取消' },
        //         { text: '确定' },

        //     ]
        // });
        // confirm.present();
    }
    initializeApp() {

        this.platform.ready().then(() => {
            // Okay, so the platform is ready and our plugins are available.
            // Here you can do any higher level native things you might need.
            this.statusBar.styleDefault();
            this.platform
            this.splashScreen.hide();
        });
    }
    //自动登录
    lodingItem(){
        let thin = this;
        if (localStorage.getItem("token") != null && localStorage.getItem("mid") != null && localStorage.getItem("loginState") == '0'){
            console.log('loginAuto');
            fetch(this.autoLoginUrl, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                //laika:token,mid:user_id
                body: "laika=" + localStorage.getItem("token") + "&mid=" + localStorage.getItem("mid") +"&Type=app&token=9ne6b8lhaq3hefcm5ngc6k19r0" ,
            }).then(function (response) {
                response.text().then((json)=>{
                    //code 0成功 1失败
                    console.log(json);
                    if (json != '') { 
                        let state = JSON.parse(json).code
                        if (state != '0') {
                            let confirm = thin.alertCtrl.create({
                                title: '温馨提示',
                                message: '登录失败，请重新登录',
                                buttons: [
                                    { text: '确定' },

                                ]
                            });
                            confirm.present();
                            thin.loginfalse()
                        } else {
                            thin.userUpdate()
                        }
                    }else{
                        let confirm = thin.alertCtrl.create({
                            title: '温馨提示',
                            message: '登录失败，请重新登录',
                            buttons: [
                                { text: '确定' },

                            ]
                        });
                        confirm.present();
                        thin.loginfalse()
                    }
                    
                })
                
            }).catch(function (err) {
                console.log(err)
            })

            
            
        }else{
            // this.user_name = "请登录";
            // this.user_pic = "./assets/imgs/user.png";
            // this.userUpdate()
        }
        // this.user_name = user['user_name']
        // this.user_pic = user['user_pic']
        
    }

    // userUpdate(user:any){
    userUpdate(){
        let thin = this;
        
        if (localStorage.getItem("token") != null && localStorage.getItem("mid") != null && localStorage.getItem("loginState") == '0') {
            fetch(this.aplyUrl, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token"),
            }).then((response) => {
                response.text().then((con) => {
                    let user = JSON.parse(con);
                    if (user == ''){
                        let confirm = thin.alertCtrl.create({
                            title: '温馨提示',
                            message: '登录失败，请重新登录',
                            buttons: [
                                { text: '确定' },

                            ]
                        });
                        thin.loginfalse()
                        confirm.present();
                    }else{
                        localStorage.setItem("userName", user['user_name'])
                        localStorage.setItem("userPic", user['user_pic'])
                        //检测用户交易密码 0为空1为不空
                        localStorage.setItem("payPwd", user['member_paypwd'])
                    }
                    
                }).catch((err) => {
                    let confirm = thin.alertCtrl.create({
                        title: '温馨提示',
                        message: "连接错误，请联系客服",
                        buttons: [
                            { text: '确定' },

                        ]
                    });
                    confirm.present();  
                })

            }).catch((err) => {
                console.log(err)
            })
        } else {
            thin.loginfalse()
        }
        
    
        
    }
    ionDrag(){
        if (localStorage.getItem("userName") != null || localStorage.getItem("userPic") != null) {
            this.user_name = localStorage.getItem("userName")
            this.user_pic = localStorage.getItem("userPic")
            this.loginState = parseInt(localStorage.getItem("loginState"));
            console.log(1)
        } else {
            this.loginfalse()
            console.log(2)
        }
    }

    
    openPage(page) {
        // Reset the content nav to have just this page
        // we wouldn't want the back button to show in this scenario
        this.nav.setRoot(page.component);
        // this.user_name = localStorage.getItem("userName")
        // this.user_pic = localStorage.getItem("userPic")
    }
    
    openWindow(page){
        this.loginState = parseInt(localStorage.getItem("loginState"));
        console.log(this.loginState);
        if (page.title == '首页'){
            this.nav.setRoot(page.component);
        } else if (page.title == '联系客服'){ 
            let confirm = this.alertCtrl.create({
                title: '温馨提示',
                message: '是否跳转至QQ客服聊天窗口？',
                buttons: [
                    { text: '取消'},
                    {
                        text: '同意',
                        handler: () => {
                            //如果是安卓
                            // const browser = this.iab.create("https://wpa.qq.com/msgrd?v=3&uin=3602907793&site=qq&menu=yes", '_system','' );
                            const browser = this.iab.create("mqqwpa://im/chat?chat_type=wpa&uin=3602907793&version=1&src_type=web&web_src=oicqzone.com", '_system','' );
                            console.log('Agree clicked');
                        }
                    }
                ]
            });
            confirm.present();
        }else if(page.title == "全民娱乐"){
            this.nav.push(page.component);
        }else{
            if (this.loginState == 0){
                this.nav.push(page.component);
            }else{
                this.nav.push(LoginPage);
            }
            
        }
        
    }
    UserInfoWindow(){
        
        this.loginState = parseInt(localStorage.getItem("loginState"));
        //this.nav.push(this.User[this.loginState].component);
        if (this.loginState != 0){
            this.nav.push(this.User[1].component);
        }else{
            this.nav.push(this.User[0].component);
        }
        
    }


    loginfalse(){
        localStorage.setItem("loginState", "1");
        localStorage.setItem("userName", "请登录")
        localStorage.setItem("userPic", "./assets/imgs/user.png")
        console.log(localStorage.getItem("loginState"))
    }
    
    
}
